package day12.network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class ChatServer {
    ArrayList<ComThread> list = new ArrayList<>();
    public void start(){
        new Thread(){
            @Override
            public void run() {
                try {
                    ServerSocket server = new ServerSocket(8000);
                    while(true){
                        Socket s = server.accept();
                        ComThread t = new ComThread(s);
                        synchronized (list){
                            list.add(t);
                        }
                        t.start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    class ComThread extends Thread{
        String name;
        Socket s;
        BufferedReader in;
        PrintWriter out;
        public ComThread(Socket s){
            this.s = s;
        }
        public void send(String msg){
            out.println(msg);
            out.flush();
        }
        //向所有的客户端发送
        public void sendAll(String msg){
            for (ComThread t: list) {
                t.send(msg);
            }
        }

        @Override
        public void run() {
            try{
                in = new BufferedReader(new InputStreamReader(s.getInputStream(), "GBK"));
                out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), "GBK"));
                //接收客户端昵称
                name = in.readLine();
                //群发消息xx进入聊天室
                synchronized (list){
                    sendAll(name+"进入聊天室, 在线人数"+list.size());
                }

                //循环接收聊天内容，并群发
                String line;
                while ((line = in.readLine()) != null){
                    synchronized (list){
                        sendAll(name+"说:"+line);
                    }
                }
            }catch (Exception e){
            }
            synchronized (list){
                // 当前客户端连接断开
                // 当前通信线程对象从集合移除
                list.remove(this);
                // 群发消息, xx离开
                sendAll(name+"离开聊天室,剩余人数"+list.size());
            }

        }
    }

    public static void main(String[] args) {
        ChatServer chatServer = new ChatServer();
        chatServer.start();

    }
}
